package com.qqtech.qquan.mall.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.community.dao.CommunityBaseDao;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.mall.dao.MallShopCommunityDao;
import com.qqtech.qquan.mall.model.MallShopCommunity;
import com.qqtech.qquan.mall.model.MallShopCommunityQuery;
import com.qqtech.qquan.mall.model.MallShopCommunityVo;

@Service
public class MallShopCommunityServiceImpl extends BaseServiceImpl<MallShopCommunity>
		implements MallShopCommunityService {
	public static final Logger log = LoggerFactory.getLogger(MallShopCommunityServiceImpl.class);
	
	@Resource
	private MallShopCommunityDao mallShopCommunityDao;
	
	@Resource
	private CommunityBaseDao communityBaseDao;

	@Override
	protected BaseDao<MallShopCommunity> getBaseDao() {
		return mallShopCommunityDao;
	}

	@Override
	public List<MallShopCommunityVo> queryListByShopId(Integer shopId) {
		if (shopId == null) {
			return null;
		}
		MallShopCommunityQuery q = new MallShopCommunityQuery();
		q.setShopId(shopId);
		List<MallShopCommunityVo> list = mallShopCommunityDao.queryList(q);
		if (list != null && !list.isEmpty()) {
			for (MallShopCommunityVo v : list) {
				CommunityBaseVo c = communityBaseDao.getById(v.getCommunityId());
				v.setCommunityBaseVo(c);
			}
		}
		return list;
	}

	@Override
	public int handleSave(Integer shopId, List<Integer> communityIdList) {
		int v = 0;
		if (shopId != null && communityIdList != null && !communityIdList.isEmpty()) {
			// 先删掉之前的
			MallShopCommunityQuery q = new MallShopCommunityQuery();
			q.setShopId(shopId);
			mallShopCommunityDao.delete(q);
			List<MallShopCommunity> entityList = new ArrayList<MallShopCommunity>(communityIdList.size());
			Timestamp now =TimeUtil.now();
			for (Integer cId : communityIdList) {
				MallShopCommunity temp = new MallShopCommunity();
				temp.setCommunityId(cId);
				temp.setShopId(shopId);
				temp.setNewAt(now);
				entityList.add(temp);
			}
			v = mallShopCommunityDao.insertInBatch(entityList);
		}
		return v;
	}

	@Override
	public boolean checkHas(Integer shopId, Integer communityId) {
		if (shopId == null || communityId == null) {
			return false;
		}
		MallShopCommunityQuery q = new MallShopCommunityQuery();
		q.setShopId(shopId);
		q.setCommunityId(communityId);
		int c = mallShopCommunityDao.queryCount(q);
		return c > 0;
	}
	
}